package com.zhangdi.demo.solr.service;

import com.mongodb.client.MongoCollection;
import com.zhangdi.demo.solr.response.Response;
import com.zhangdi.demo.solr.response.ResponseUtils;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

/**
 * Created by zhangdi on 2020/07/01 11:17:22.
 */

@Service
public class MongoServiceImpl implements MongoService {
    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public boolean collectionExists(String collectionName) {
        return mongoTemplate.collectionExists(collectionName);
    }

    @Override
    public Response createCollection(String collectionName) {
        if (!mongoTemplate.collectionExists(collectionName)) {
            MongoCollection<Document> collection = mongoTemplate.createCollection(collectionName);
            if (null == collection) {
                ResponseUtils.error("创建集合失败");
            }
        }
        return ResponseUtils.success();
    }

    @Override
    public Response dropCollection(String collectionName) {
        try {
            if (mongoTemplate.collectionExists(collectionName)) {
                mongoTemplate.dropCollection(collectionName);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtils.error("删除集合失败");
        }
        return ResponseUtils.success();
    }
}
